import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import { getToken, removeToken, getStorageUserInfo } from '@/utils/auth'
import NProgress from 'nprogress' // 网络请求进度条
import 'nprogress/nprogress.css' // 网络请求进度条 style
import store from '@/store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 创建一个axios实例
const service = axios.create({
  baseURL: 'http://jx.qida999.com/drivercommon/CommApiNew/',
  timeout: 5000,
})

// 请求拦截器
service.interceptors.request.use(
  config => {

    // 进度条开始
    NProgress.start()
    // 全屏loading加载

    // 让每个请求都带有令牌
    config.data.token = getToken()
    if (config.data.token) {
      config.data.userno = getStorageUserInfo().userno
    }
    
    // 将JSON转成form-data格式
    const formData = new FormData()
    Object.keys(config.data).forEach(key => {
      if (typeof config.data[key] === 'string') {
        formData.append(key, config.data[key])
      } else {
        formData.append(key, JSON.stringify(config.data[key]))
      }
    })
    config.data = formData
    
    // console.log('请求成功 :>> ', config);
    return config
  },
  error => {
    NProgress.done()

    // 请求失败
    console.log('请求失败', error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  // 接口返回的数据和状态
  response => {
    const res = response.data

    NProgress.done()

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      Message({
        message: res.msg || '请求错误',
        type: 'error',
      })

      // 401: token不存在或失效 ; undefined: 后台报错返回 undefined;
      if (res.code === undefined || res.code === 401) {
        const Msundefined = res.code === 401 ? '登录信息已过期，请重新登录' : '服务端内部错误,请联系技术人员'
        
        Message({
          message: Msundefined,
          type: 'error',
          duration:3000,
        })

        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })

      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      // console.log('响应成功', res)

      // 请求成功 返回数据
      return res
    }
  },
  error => {
    // console.log('响应失败' + error) // for debug

    // 对响应错误做点什么 statusCode !== 200
    if (error) {
      const { errNo: status } = error
      switch (status) {
        case 401:
          Message({
            message: '登录信息已过期，请重新登录',
            type: 'error',
          })
          break
        case 403:
          Message({
            message: '没有权限，请联系管理员',
            type: 'error',
          })
          break
        case 404:
          Message({
            message: '请求资源不存在',
            type: 'error',
          })
          break
        default:
          Message({
            message: error.message,
            type: 'error',
          })
          break
      }
    }
    NProgress.done()
    // console.log('响应失败')
    response.config.Loading.close()

    return Promise.reject(error)
  }
)

export default service
